package org.pms.demo.webservice.service.impl;

import org.pms.demo.webservice.dao.pms.RoleMapper;
import org.pms.demo.webservice.domain.Role;
import org.pms.demo.webservice.service.RoleVersionService;
import org.pms.demo.webservice.utils.ProjectUtils;
import org.pms.demo.webservice.utils.StringUtils;
import org.pms.demo.webservice.vo.PageContent;
import org.pms.demo.webservice.vo.RoleInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by laijianpeng on 17/10/18.
 */
@Service
public class RoleVersionServiceImpl implements RoleVersionService{
    @Resource
    private RoleMapper roleMapper;

    @Override
    public String getRoleList(int page, int page_size) {
        if(page<=0&&page_size<=0){
            return ProjectUtils.getErrorMsg("param");
        }
        PageContent pageContent = new PageContent();
        pageContent.setTotal(roleMapper.getRoleListNum());
        int index = (page-1)*page_size;
        List<Role> list = roleMapper.getRoleListByPage(index,page_size);
        List<Object> roleInfos = new ArrayList<>();
        for(Role role:list){
            RoleInfo roleInfo = new RoleInfo();
            roleInfo.setDescription(role.getDescription());
            roleInfo.setId(role.getId()+"");
            roleInfo.setRole(role.getRole());
            roleInfos.add(roleInfo);
        }
        pageContent.setRows(roleInfos);


        return ProjectUtils.getContentMsg(pageContent);
    }

    @Override
    public String deleteRoleById(String id) {
        Long id_long = 0L;
        try{
            id_long = Long.valueOf(id);
        }catch (Exception e){
            return ProjectUtils.getErrorMsg("param");
        }

        if(id_long<=1){
            return ProjectUtils.getErrorMsg("param");
        }
        Role role = roleMapper.getRoleById(id_long);
        if(role==null){
            return ProjectUtils.getErrorMsg("param");
        }
        role.setId(id_long);
        role.setAvailable(0);
        roleMapper.updateRoleById(role);
        return ProjectUtils.getContentMsg("删除成功");

    }

    @Override
    public String updateRole(String id, String role_name, String description) {
        Long id_long = 0L;
        try{
            id_long = Long.valueOf(id);
        }catch (Exception e){
            return ProjectUtils.getErrorMsg("param");
        }
        Role role = roleMapper.getRoleById(id_long);
        if(role==null){
            return ProjectUtils.getErrorMsg("param");
        }
        if(StringUtils.isNullOrEmpty(role_name)||StringUtils.isNullOrEmpty(description)){
            return ProjectUtils.getErrorMsg("param");
        }
        role.setRole(role_name);
        role.setDescription(description);
        roleMapper.updateRoleById(role);

        return ProjectUtils.getContentMsg("修改成功");
    }
}
